package io.dcloud.uniplugin;

import static io.dcloud.uniplugin.CameraActivity.COMMAND;
import static io.dcloud.uniplugin.CameraActivity.PHOTO_PATH;
import static io.dcloud.uniplugin.CameraActivity.TYPE;
import static io.dcloud.uniplugin.CameraActivity.VIN_CODE;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;
import io.dcloud.common.core.permission.PermissionControler;


public class TestModule extends UniModule {

    String TAG = "TestModule";
    private UniJSCallback uniJSCallback;
    private int type;
    private String vinCode = "";
    private String command = "";
    public static int REQUEST_CODE = 1000;
    private String path = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            Log.e("TestModule", "原生页面返回----" + data.getStringExtra(PHOTO_PATH));
            path = data.getStringExtra(PHOTO_PATH);
            if (uniJSCallback != null) {
                JSONObject jsonObject = new JSONObject();
                try {
                    if (type == 0) {
                        jsonObject.put("path", data.getStringExtra(PHOTO_PATH));
                    } else {
                        jsonObject.put("VIN", data.getStringExtra(VIN_CODE));
                    }
                    uniJSCallback.invokeAndKeepAlive(jsonObject.toString());
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
//            Map<String, Object> params = new HashMap<>();
//            params.put("path", data.getStringExtra(PHOTO_PATH));
//            mUniSDKInstance.fireGlobalEventCallback("vinPicEvent", params);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 跳转页面
     */
    @UniJSMethod(uiThread = true)
    public void gotoNativePage() {
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            Intent intent = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
                intent = new Intent(mUniSDKInstance.getContext(), CameraActivity.class);
            }
            ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
        }
    }

    /**
     * 删除缓存图片
     */
    @UniJSMethod(uiThread = true)
    public void deleteCache() {
        String path = Objects.requireNonNull(mUniSDKInstance.getContext().getExternalFilesDir("offline_package")).getAbsolutePath();
        Runnable runnable = () -> deleteDirs(path);
        ThreadPoolInstance.getInstance().getThreadPoolExecutor().execute(runnable);
    }

    final int PERMISSION_REQUEST_CODE = 11111;
    private static String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.CAMERA};

    /**
     * 请求拍照
     *
     * @param vinCode  车架号
     * @param callback 数据回调
     */
    @UniJSMethod(uiThread = true)
    public void requestTakePhoto(String vinCode, String password, UniJSCallback callback) {
        this.uniJSCallback = callback;
        this.vinCode = vinCode;
        this.command = password;
        type = 0;
        if (mUniSDKInstance.getContext() != null) {
            Activity activity = (Activity) mUniSDKInstance.getContext();
            PermissionControler.requestPermissions(activity, permissions, PERMISSION_REQUEST_CODE);
        }
    }

    /**
     * 请求扫描车架号
     */
    @UniJSMethod(uiThread = true)
    public void requestScanVIN(UniJSCallback callback) {
        this.uniJSCallback = callback;
        type = 1;
        if (mUniSDKInstance.getContext() != null) {
            Activity activity = (Activity) mUniSDKInstance.getContext();
            PermissionControler.requestPermissions(activity, permissions, PERMISSION_REQUEST_CODE);
        }
    }

    /**
     * 获取图片
     */
    @UniJSMethod(uiThread = true)
    public void getPicPath(UniJSCallback callback) {
        if (callback != null) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("path", path);
                callback.invoke(jsonObject.toString());
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                String preName = permissions[i];
                int granted = grantResults[i];
                if (granted != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(mUniSDKInstance.getContext(), "请开启相应权限，否则无法使用", Toast.LENGTH_LONG).show();
                    //获取权限结果
                    return;
                }
            }
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), CameraActivity.class);
                if (type == 0) {
                    intent.putExtra(VIN_CODE, vinCode);
                    intent.putExtra(COMMAND, command);
                }
                intent.putExtra(TYPE, type);
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    /**
     * 删除某个目录
     *
     * @param path 要删除的目录路径
     * @return
     */
    public Boolean deleteDirs(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return true;
        }
        if (file.isDirectory()) {
            File[] childs = file.listFiles();
            if (childs != null) {
                boolean result = true;
                for (File child : childs) {
                    result = result && deleteDirs(child.getAbsolutePath());
                }
                try {
                    boolean ret = file.delete();
                    return result && ret;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            } else {
                return false;
            }
        } else {
            try {
                return file.delete();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }
}
